/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.util;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class CharacterTree<T> {
    private TreeEntry root = new TreeEntry();

    public void put(CharSequence key, T value) {
        TreeEntry curr = root;
        for (int i = 0; i < key.length(); i++) {
            char ch = key.charAt(i);
            TreeEntry next = curr.getRef(ch);
            if (next == null) {
                next = new TreeEntry();
                curr.setRef(ch, next);
            }
            curr = next;
        }
        curr.setValue(value);
    }

    public T get(CharSequence key) {
        TreeEntry curr = root;
        int index = 0;
        while (curr != null) {
            if (index >= key.length())
                return (T) curr.getValue();
            curr = curr.getRef(key.charAt(index++));
        }
        return null;
    }

    private static class TreeEntry {
        //Each array element corresponds to a character from a to z, the last element is a hyphen.
        private TreeEntry[] refs = new TreeEntry[27];
        private Object value;

        public TreeEntry getRef(char ch) {
            final int index = makeIndex(ch);
            if (index != -1)
                return refs[index];
            else
                return null;
        }

        public void setRef(char ch, TreeEntry entry) {
            final int index = makeIndex(ch);
            if (index != -1)
                refs[index] = entry;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        private int makeIndex(char ch) {
            int result = -1;
            if (ch == 45) //hyphen
                result = 26;
            else if (ch >= 97 && ch <= 122) //small latin letters
                result = ch - 97;
            else if (ch >= 65 && ch <= 90) //capital latin letters
                result = ch - 65;
            return result;
        }
    }
}
/*
 * $Log$
 */